import React, { FC, useState, useEffect, useRef, useMemo } from "react";
import QuestionCard from "../../../components/QuestionCard";
import style from "../common.module.scss";

import { useDebounceFn, useRequest, useTitle } from "ahooks";
import { Spin, Typography, Empty } from "antd";
import ListSearch from "../../../components/ListSearch";
// import { getQuestionListServices } from "../../../services/question";
// import { useRequest } from "ahooks";
// import useLoadQuestionListData from "../../../hooks/useLoadQuestionListData";
import { useSearchParams } from "react-router-dom";
import { getQuestionListServices } from "../../../services/question";
import { LIST_PAGE_SIZE, LIST_SEARCH_PARAM_KEY } from "../../../constant";
const { Title } = Typography;

const List: FC = () => {
  useTitle("小b问卷列表");

  // const { data = {}, erorr, loading } = useLoadQuestionListData();
  // const { list = [], total = 0 } = data;
  const [strated, setStrated] = useState(false); //记录是否已经加载开始
  const [list, setList] = useState([]);
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);

  const haveMoreData = list.length < total;

  const [serachParams] = useSearchParams();
  const keyword = serachParams.get(LIST_SEARCH_PARAM_KEY) || "";

  useEffect(() => {
    setStrated(false);
    setPage(1);
    setTotal(0);
    setList([]);
  }, [keyword]);

  const { run: load, loading } = useRequest(
    async () => {
      const res = await getQuestionListServices({
        page,
        pageSize: LIST_PAGE_SIZE,
        keyword,
      });
      return res;
    },
    {
      manual: true,
      onSuccess(result) {
        const { list: l = [], total } = result;
        setList(list.concat(l));
        setTotal(total);
        setPage(page + 1);
      },
    }
  );
  const contianerRef = useRef<HTMLDivElement>(null);
  //加载触发
  const { run: tryLoadMore } = useDebounceFn(
    () => {
      const elem = contianerRef.current;
      if (elem == null) return;
      const domRect = elem.getBoundingClientRect();
      if (domRect == null) return;
      const { bottom } = domRect;

      if (bottom <= window.innerHeight) {
        console.log("执行加载1", bottom, document.body.clientHeight);
        load(); //真正加载数据
        setStrated(true);
      }
    },
    { wait: 1000 }
  );

  //当页面加载触发
  useEffect(() => {
    tryLoadMore();
  }, [serachParams, tryLoadMore]);

  //监听绑定事件
  useEffect(() => {
    if (haveMoreData) {
      window.addEventListener("scroll", tryLoadMore);
    }
    return () => {
      window.removeEventListener("scroll", tryLoadMore); // 解绑事件，重要！！！
    };
  }, [serachParams, haveMoreData, tryLoadMore]);

  //   const [list, setList] = useState([]);
  //   const [total, setTotal] = useState(0);
  //   useEffect(() => {
  //     async function load() {
  //       const data = await getQuestionListServices();
  //       const { list = [], total = [] } = data;
  //       setList(list);
  //       setTotal(total);
  //     }
  //     load();
  //   }, []);

  const loadMoreContentElem = useMemo(() => {
    if (!strated || loading) return <Spin />;
    if (total === 0) return <Empty description="暂无数据" />;
    if (!haveMoreData) return <div>没有更多数据了... </div>;
    return <span>开始加载下一页</span>;
  }, [strated, haveMoreData, loading, total]);
  return (
    <>
      <div className={style.header}>
        <div className={style.left}>
          {/* <h3>我的问卷</h3> */}
          <Title level={3}>我的问卷</Title>
        </div>
        <div className={style.right}>
          <ListSearch />
        </div>
      </div>

      <div className={style.content}>
        {/* 问卷列表 */}
        {list.length > 0 &&
          list.map((item: any) => {
            const { _id: _id } = item;
            return <QuestionCard key={_id} {...item} />;
          })}
      </div>

      <div className={style.footer}>
        <div ref={contianerRef}> {loadMoreContentElem}</div>
      </div>
    </>
  );
};

export default List;
